package com.cqupt.command.imp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cqupt.command.Command;
import com.cqupt.utils.FileReadMan;
import com.cqupt.utils.Result;

public class CutCommand implements Command {
	// 选项列表
	private Map<String, String> options;
	// 参数列表
	private String parameters;
	// 上命令的结果
	private String result;

	public CutCommand(String command, String result) {
		// 命令解析得到选项
		this.options = getOptions(command);
		// 命令解析得到参数
		this.parameters = getParameters(command);
		// 得到上个命令的结果
		this.result = result;
	}

	private Map<String, String> getOptions(String command) {
		Map<String, String> result = new HashMap<>();
		Pattern pattern = Pattern.compile("-[b,c,f].*?(?= )|-[n,d].*?(?= )");
		Matcher matcher = pattern.matcher(command);
		while (matcher.find()) {
			String parameterA = matcher.group();
			// 特殊的-bn
			String key = parameterA.substring(0, 2);
			String value = parameterA.substring(2, parameterA.length());
			if (parameterA.charAt(1) == 'b' && parameterA.charAt(1) == 'n') {
				key = parameterA.substring(0, 3);
				value = parameterA.substring(3, parameterA.length());
			}
			result.put(key, value);
		}
		return result;
	}

	private String getParameters(String command) {
		String[] cmd = command.split(" ");
		return cmd[cmd.length - 1].trim();
	}

	// -b按照字节切割，-n不安字符切割,-c按照字符切割，-f按照分隔符切割， -d指定分隔符（默认是tab键）
	@Override
	public String run() {
		// 获取数据源
		List<String> listString = new ArrayList<>();
		if (result != null) {
			String[] resultSource = result.split("\r?\n");
			for (int i = 0; i < resultSource.length; i++) {
				String sourceLine = resultSource[i];
				if (!"".equals(sourceLine)) {
					listString.add(sourceLine.trim());
				}
			}
		} else {
			FileReadMan fileReadMan = new FileReadMan(parameters);
			while (fileReadMan.hasNext()) {
				String sourceLine = fileReadMan.next();
				if (!"".equals(sourceLine)) {
					listString.add(sourceLine.trim());
				}
			}
		}
		// 确定b，c，f中的一个
		Result<String> result = new Result<String>();
		for (String key : options.keySet()) {
			switch (key) {
			case "-b":
				List<String> cutResultB = getByteBN(key, listString, false);
				return result.getResult(cutResultB);
			case "-bn":
				List<String> cutResultBN = getByteBN(key, listString, true);
				return result.getResult(cutResultBN);
			case "-c":
				List<String> cutResultC = getByteC(key, listString);
				return result.getResult(cutResultC);
			case "-f":
				List<String> cutResultF = getByteF(key, listString);
				return result.getResult(cutResultF);
			}
		}
		return null;
	}

	private List<String> getByteF(String key, List<String> listString) {
		String did = "\t";
		if (options.containsKey("-d")){
			did = options.get("-d").split("\"")[1];
		}
		List<String> result = new ArrayList<String>();
		String value = options.get(key);
		String[] span = value.split("-");
		int begin = 0;
		int end = Integer.MAX_VALUE;
		if (value.matches("\\d+-\\d+")) {
			begin = Integer.parseInt(span[0]);
			end = Integer.parseInt(span[2]);
		} else if (value.matches("-\\d+")) {
			end = Integer.parseInt(span[1]);
		} else if (value.matches("\\d+-")) {
			begin = Integer.parseInt(span[0]);
		} else if (value.matches("\\d+")) {
			begin = Integer.parseInt(span[0]);
			end = Integer.parseInt(span[0]);
		}
		for (int i = 0; i < listString.size(); i++) {
			String line = listString.get(i);
			String[] lineStrings = line.split(did);
			if (end > lineStrings.length) {
				end = lineStrings.length;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int j=begin-1; j<=end-1;j++) {
				stringBuilder.append(lineStrings[j]);
			}
			result.add(stringBuilder.toString());
		}
		return result;
	}

	private List<String> getByteC(String key, List<String> listString) {
		List<String> result = new ArrayList<String>();
		String value = options.get(key);
		String[] span = value.split("-");
		int begin = 1;
		int end = Integer.MAX_VALUE;
		if (value.matches("\\d+-\\d+")) {
			begin = Integer.parseInt(span[0]);
			end = Integer.parseInt(span[1]);
		} else if (value.matches("-\\d+")) {
			end = Integer.parseInt(span[1]);
		} else if (value.matches("\\d+-")) {
			begin = Integer.parseInt(span[0]);
		} else if (value.matches("\\d+")) {
			begin = Integer.parseInt(span[0]);
			end = Integer.parseInt(span[0]);
		}
		for (int i = 0; i < listString.size(); i++) {
			String line = listString.get(i);
			char[] lineChars = line.toCharArray();
			if (end > lineChars.length) {
				end = lineChars.length;
			}
			//是多字节字符，不能分割
			result.add(new String(lineChars, begin-1, end-begin+1));
		}
		return result;
	}

	private List<String> getByteBN(String key, List<String> listString, boolean flag) {
		List<String> result = new ArrayList<String>();
		String value = options.get(key);
		String[] span = value.split("-");
		int begin = 1;
		int end = Integer.MAX_VALUE;
		if (value.matches("\\d+-\\d+")) {
			begin = Integer.parseInt(span[0]);
			end = Integer.parseInt(span[1]);
		} else if (value.matches("-\\d+")) {
			end = Integer.parseInt(span[1]);
		} else if (value.matches("\\d+-")) {
			begin = Integer.parseInt(span[0]);
		} else if (value.matches("\\d+")) {
			begin = Integer.parseInt(span[0]);
			end = Integer.parseInt(span[0]);
		}
		for (int i = 0; i < listString.size(); i++) {
			String line = listString.get(i);
			byte[] lineBytes = line.getBytes();
			if (end > lineBytes.length) {
				end = lineBytes.length;
			}
			//是多字节字符，不能分割
			if (flag && lineBytes[end-2] != 0)
				end = end - 1;
			result.add(new String(lineBytes, begin-1, end-begin+1));
		}
		return result;
	}

}
